# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _

from .draw_nuonuo import create_fapiao, read_fapiao, invalid_fapiao
from .draw_nuonuo import print_batch_fapiao, print_fapiao

from .draw_nuonuo import access_token_check
import datetime


import logging

_logger = logging.getLogger(__name__)


def nuonuo_request_method(fapiao):
    result = create_fapiao(fapiao)

    for rec in result:
        one = fapiao.browse(rec['id'])
        serial_num = rec['serial_num']

        one.write({
            'nuonuo_serial_num': serial_num,
            'nuonuo_api_status': 'doing',
            'nuonuo_api_status_msg': '开票中'})

    return result


def nuonuo_query_method(fapiao):
    records = read_fapiao(fapiao)

    for one in records:
        if one['api_status'] in ['done']:
            one['state'] = 'done'
        elif one['api_status'] in ['be_invalid']:
            # todo 暂时用不到. 什么叫做已经取消?
            one['state'] = 'be_invalid'
        elif one['api_status'] in ['doerror', 'signerror']:
            one['state'] = 'error'
        else:
            # doing, signing, being_invalid
            one['state'] = 'reread'

        for line in one['line_ids']:
            line['id'] = int(line['line_num'])

    for record in records:
        values_for_draw = {
            'nuonuo_api_status': record['api_status'],
            'nuonuo_api_status_msg': record['api_status_msg'],
            'nuonuo_api_fail_cause': record['api_fail_cause'],
        }

        one = fapiao.browse(record['id'])
        one.write(values_for_draw)

    return records


def nuonuo_invalid_method(fapiao):
    # print('nuonuo_invalid_method', fapiao)
    # _logger.info('nuonuo_invalid_method:%s,', fapiao)
    # time.sleep(3)
    records = invalid_fapiao(fapiao)

    # _logger.info('nuonuo_invalid_method ret:%s,', records)

    return records


def nuonuo_print_patch_method(fapiao):
    print('nuonuo_print_patch_method', fapiao)
    # time.sleep(3)
    res = print_batch_fapiao(fapiao)

    # string  return

    # {
    #     'ids': [],
    #     'result':  '',  batch id, a string for print encryptdata
    # }

    return [{'id': one.id} for one in fapiao]


def nuonuo_print_method(fapiao):
    print('nuonuo_print_method', fapiao)
    # time.sleep(3)
    records = print_fapiao(fapiao)

    print('nuonuo_print_method', records)
    # return [{'id': one.id} for one in fapiao]

    return records


class FapiaoApiDraw(models.Model):
    _inherit = "fp.api.draw"

    nuonuo_print_rsa_pub_key = fields.Char(
        string='Nuonuo Print RSA Pub Key',  help="Print RSA Pub Key")

    # 尚未做 view . 显示该 字段 print_rsa_pub_key

    def _request_methods(self):
        result = super()._request_methods()
        result2 = result.copy()
        result2.update({'nuonuo': nuonuo_request_method})
        return result2

    def _query_methods(self):
        result = super()._query_methods()
        result2 = result.copy()
        result2.update({'nuonuo': nuonuo_query_method})
        return result2

    def _invalid_methods(self):
        result = super()._invalid_methods()
        result2 = result.copy()
        result2.update({'nuonuo': nuonuo_invalid_method})
        return result2

    def _print_methods(self):
        result = super()._print_methods()
        result2 = result.copy()
        result2.update({'nuonuo': nuonuo_print_method})
        return result2


class ApiDrawCompany(models.Model):
    _inherit = "fp.api.draw.company"

    nuonuo_app_key = fields.Char(string='nuonuo App Key')
    nuonuo_app_secret = fields.Char(string='nuonuo App Secret')

    nuonuo_user_id = fields.Char(string='nuonuo User_id')
    nuonuo_access_token = fields.Char(string='nuonuo Access Token')
    nuonuo_refresh_token = fields.Char(string='nuonuo Refresh Token')
    nuonuo_expires_in = fields.Integer(string='nuonuo Expires_in')
    nuonuo_lasttime = fields.Datetime(string='nuonuo Lasttime')

    nuonuo_print_aes_key = fields.Char(string='nuonuo Print AES Key')

    def nuonuo_access_token_check(self):
        res = access_token_check(self)
        _logger.info("Nuonuo Token is checked: %s" % res)

        if res:
            now = datetime.datetime.now()
            self.write({
                'nuonuo_access_token': res['access_token'],
                'nuonuo_refresh_token': res['refresh_token'],
                'nuonuo_expires_in': res['expires_in'],
                'nuonuo_lasttime': now.strftime('%Y-%m-%d %H:%M:%S'),
            })

        return res
